package Networking;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Server {
	
	public static void main(String argv[]) throws Exception	{
		
/*	  String clientSentence;
	  String capitalizedSentence;
*/
		//We will use this to store the web address that the client will send us.
		String webAddress;
		
		//Create the server's "guidepost" socket. It should share a port with the client socket.
		ServerSocket welcomeSocket = new ServerSocket(12337);
		
		//Set up a specialized socket for communication between the client and the server.	  
	    Socket connectionSocket = welcomeSocket.accept();
	    
	    //Get the web address from the client.
	    BufferedReader inFromClient = new BufferedReader(
	    		new InputStreamReader(
	    				connectionSocket.getInputStream()));
	    webAddress = inFromClient.readLine();
	    connectionSocket.close();	    
	    System.out.println("The web address received from the Client is: \n" + webAddress + "\n");   
	  
	    //Print out the info from the web address that the client sent us.
	    accessWeb(webAddress);
	    
	  /*
	  while (true) {
	    Socket connectionSocket = welcomeSocket.accept();
		BufferedReader inFromClient =
		    new BufferedReader(new InputStreamReader(
			    connectionSocket.getInputStream()));
		DataOutputStream outToClient =
		    new DataOutputStream(
			    connectionSocket.getOutputStream());
			clientSentence =inFromClient.readLine();
			capitalizedSentence=clientSentence.toUpperCase()+'\n';
	    outToClient.writeBytes(capitalizedSentence);
	  }*/
	  
	}
	
	public static void accessWeb(String webAddress) throws Exception{
		String sentence;
		String modifiedSentence;
		BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
	   
		//Create Socket
		Socket clientSocket = new Socket(webAddress, 80);
		
		//Set up our output stream so we can send things through the socket.
		DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
		
		//Set up our input stream so we can receive things through the socket.
		BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
	   
		//Initialize the sentence that we're going to send out to the server.
		//Sentence is our message. In this case, it's a 'GET //' command. 
		sentence = "GET //";
		System.out.println(sentence);	
		
		//Convert our sentence to bytes and send it to the sever.
		outToServer.writeBytes(sentence+'\n');
		
		//Get and print whatever the server returns to us.
		System.out.print("From Server: ");
		while((modifiedSentence = inFromServer.readLine()) != null){
			System.out.println(modifiedSentence);
		}  
	   
		//Close the socket.
		clientSocket.close();
	}
}
